import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../../bi.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { deepClone } from '../../../../../utils/utils';
import { XlsxService } from '@shared/apes/xlsx';
import { ApesMessageService } from '@shared/apes/message';
import { toNumber } from '@shared/apes/core/util/convert';

@Component({
  selector: 'trend-analysis',
  templateUrl: './trend-analysis.component.html',
  styleUrls: ['./trend-analysis.component.scss'],
})
export class TrendAnalysisComponent implements OnInit {

  // 趋势分析

  initData: any[] = [
    // 营业款
    {
      id: 'turnover',
      name: '营业款',
      tooltip: '【货币资金（不含定损代收）】+【应收账款（内）】+【应收账款（外）】+【会员跨公司消费 - 收入】-【会员跨公司消费 - 支出】',
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
        },
        legend: {
          data: ['本期时段', '上期时段', '同比', '环比'],
        },
        xAxis: {
          type: 'category',
        },
        yAxis: [
          {
            name: '总额',
            type: 'value',
            axisLabel: {
              formatter: '{value}',
            },
          },
          {
            name: '百分比',
            type: 'value',
            axisLabel: {
              formatter: '{value} %',
            },
          },
        ],
        series: [
          { name: '本期时段', type: 'bar', label: { show: true } },
          { name: '上期时段', type: 'bar', label: { show: true } },
          { name: '同比', type: 'line', yAxisIndex: 1 },
          { name: '环比', type: 'line', yAxisIndex: 1 },
        ],
      },
      field: [],
      timeField: [{
        key: 'DATE',
        type: 'conditionInput',
        templateOptions: {
          label: '统计时间',
          config: {
            operators: ['EQ'],
            type: 'monthRange',
          },
          divCol: 24,
        },
      }],
      model: {},
      loading: false,
      api: 'fn.trendAnalysis.saleMoneyHistogram',
      chartsField: ['CREATE_DATE', 'SALE_MONEY', 'LAST_SALE_MONEY', 'YEAR_RATE', 'MONTH_RATE'],
      tableField: ['时间', '本期时段', '上期时段', '同比', '环比'],
      colField: [],
      rowData: [],
    },
    // 服务业绩总额
    {
      id: 'service',
      name: '服务业绩总额',
      tooltip: '营业额 - 接案介绍费 + 定损金额',
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
        },
        legend: {
          data: ['本期时段', '上期时段', '同比', '环比'],
        },
        xAxis: {
          type: 'category',
        },
        yAxis: [
          {
            name: '总额',
            type: 'value',
            axisLabel: {
              formatter: '{value}',
            },
          },
          {
            name: '百分比',
            type: 'value',
            axisLabel: {
              formatter: '{value} %',
            },
          },
        ],
        series: [
          { name: '本期时段', type: 'bar', label: { show: true } },
          { name: '上期时段', type: 'bar', label: { show: true } },
          { name: '同比', type: 'line', yAxisIndex: 1 },
          { name: '环比', type: 'line', yAxisIndex: 1 },
        ],
      },
      field: [],
      timeField: [{
        key: 'DATE',
        type: 'conditionInput',
        templateOptions: {
          label: '统计时间',
          config: {
            operators: ['EQ'],
            type: 'monthRange',
          },
          divCol: 24,
        },
      }],
      model: {},
      loading: false,
      api: 'fn.trendAnalysis.servicePerformanceMoneyHistogram',
      chartsField: ['CREATE_DATE', 'SERVICE_PERFORMANCE_MONEY', 'LAST_SERVICE_PERFORMANCE_MONEY', 'YEAR_RATE', 'MONTH_RATE'],
      tableField: ['时间', '本期时段', '上期时段', '同比', '环比'],
      colField: [],
      rowData: [],
    },
    // 接车数量
    {
      id: 'carNumber',
      name: '接车数量',
      tooltip: '接车数量',
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
        },
        legend: {
          data: ['本期时段', '上期时段', '同比', '环比'],
        },
        xAxis: {
          type: 'category',
        },
        yAxis: [
          {
            name: '接车数量',
            type: 'value',
            axisLabel: {
              formatter: '{value} 台',
            },
          },
          {
            name: '百分比',
            type: 'value',
            axisLabel: {
              formatter: '{value} %',
            },
          },
        ],
        series: [
          { name: '本期时段', type: 'bar', label: { show: true } },
          { name: '上期时段', type: 'bar', label: { show: true } },
          { name: '同比', type: 'line', yAxisIndex: 1 },
          { name: '环比', type: 'line', yAxisIndex: 1 },
        ],
      },
      field: [],
      timeField: [{
        key: 'DATE',
        type: 'conditionInput',
        templateOptions: {
          label: '统计时间',
          config: {
            operators: ['EQ'],
            type: 'monthRange',
          },
          divCol: 24,
        },
      }],
      model: {},
      loading: false,
      api: 'fn.trendAnalysis.pickUpCarHistogram',
      chartsField: ['CREATE_DATE', 'CAR_NUMBER', 'LAST_CAR_NUMBER', 'YEAR_RATE', 'MONTH_RATE'],
      tableField: ['时间', '本期时段', '上期时段', '同比', '环比'],
      colField: [],
      rowData: [],
    },
    // 客单价
    {
      id: 'guestPrice',
      name: '客单价',
      tooltip: '每月的车牌去重\r\n①：不勾选：（总产值-洗车产值）/ 台数-纯洗车台数\r\n②：勾选：总产值 / 总台数',
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
        },
        legend: {
          data: ['本期时段', '上期时段', '同比', '环比'],
        },
        xAxis: {
          type: 'category',
        },
        yAxis: [
          {
            name: '金额',
            type: 'value',
            axisLabel: {
              formatter: '{value}',
            },
          },
          {
            name: '百分比',
            type: 'value',
            axisLabel: {
              formatter: '{value} %',
            },
          },
        ],
        series: [
          { name: '本期时段', type: 'bar', label: { show: true } },
          { name: '上期时段', type: 'bar', label: { show: true } },
          { name: '同比', type: 'line', yAxisIndex: 1 },
          { name: '环比', type: 'line', yAxisIndex: 1 },
        ],
      },
      field: [],
      timeField: [{
        key: 'DATE',
        type: 'conditionInput',
        templateOptions: {
          label: '统计时间',
          config: {
            operators: ['EQ'],
            type: 'monthRange',
          },
          divCol: 24,
        },
      }],
      model: {},
      loading: false,
      api: 'fn.trendAnalysis.guestPriceHistogram',
      chartsField: ['CREATE_DATE', 'PRICE', 'LAST_PRICE', 'YEAR_RATE', 'MONTH_RATE'],
      tableField: ['时间', '本期时段', '上期时段', '同比', '环比'],
      colField: [],
      rowData: [],
    },
  ];
  platform: any;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
    private cd: ChangeDetectorRef,
    private userAuthService: UserAuthService,
    private xlsx: XlsxService,
    private msg: ApesMessageService,
  ) {
  }

  ngOnInit() {
    this.getPlatform();
    setTimeout(() => {
      if (this.platform == 'zt') {
        this.initData.forEach((data) => {
          this.refreshChartsData(data, 'default');
        });
      }
    }, 1000);
  }

  getPlatform() {
    this.platform = this.userAuthService.getUserInfoObj() ? this.userAuthService.getUserInfoObj().platform : '';
    console.log('平台', this.platform);
    let field: any[] = [];
    if (this.platform == 'zt') {
      field = [
        {
          key: 'DEPT_ID',
          type: 'conditionInput',
          templateOptions: {
            label: '所属门店',
            config: {
              api: 'cm.dept.findAllOperate',
              init: true,
              operators: ['EQ'],
              type: 'select',
              downFormatter: 'value.name',
              multiple: true,
              valueFormatter: 'value.name',
              searchFormId: 'cm.dept.findAllServicePlan',
              rowSelection: 'multiple',
              addSame: false,
              uniqueKey: 'id',
            },
            domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
            divCol: 6,
          },
        },
        {
          key: 'COMPANY_ID',
          type: 'conditionInput',
          templateOptions: {
            label: '所属公司',
            config: {
              api: 'cm.partyRole.findAllByCompany',
              downFormatter: `'[' + value.id + ']' + value.name`,
              multiple: true,
              operators: ['EQ'],
              type: 'select',
              value: '',
              valueFormatter: `'[' + value.id + ']' + value.name`,
            },
            domain: '{"filters":[{"field":"role.id","operator":"EQ","value":"Company"}],"groups":[{"filters":[{"field":"id","operator":"EQ","value":"{{value}}"},{"field":"party.name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}],"operator":"and"}',
            placeholder: '请选择所属公司',
            divCol: 6,
          },
        },
        {
          key: 'AREA_ID',
          type: 'conditionInput',
          templateOptions: {
            label: '区域',
            config: {
              api: 'cm.deptArea.findAllByLastStage',
              downFormatter: `value?'[ ' + value.id + ' ]' + ' ' + value.name:''`,
              multiple: true,
              init: true,
              operators: ['EQ'],
              type: 'select',
              value: '',
              valueFormatter: `value?'[ ' + value.id + ' ]' + ' ' + value.name:''`,
            },
            domain: '{"filters":[{"field":"id","operator":"EQ","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
            placeholder: '请输入区域编码或名称',
            divCol: 6,
            hide: true,
          },
        },
        {
          key: 'OPERATION_ID',
          type: 'conditionInput',
          templateOptions: {
            label: '运营模式',
            config: {
              api: 'cm.enumeration.findAll',
              downFormatter: 'value.description',
              init: true,
              multiple: true,
              operators: ['LIKE'],
              type: 'select',
              value: '',
              valueFormatter: 'value.description',
            },
            domain: '{"filters":[{"field":"valid","operator":"EQ","value":true},{"field":"type.id","operator":"EQ","value":"operation"}],"groups":[],"operator":"and"}',
            placeholder: '请输入运营模式编码或名称',
            divCol: 6,
          },
        },
      ];
    } else {
      field = [
        {
          key: 'DEPT_ID',
          type: 'conditionInput',
          templateOptions: {
            label: '所属门店',
            config: {
              api: 'cm.dept.findAllOperate',
              init: true,
              required: true,
              operators: ['EQ'],
              type: 'select',
              downFormatter: 'value.name',
              valueFormatter: 'value.name',
              multiple: true,
            },
            domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
            divCol: 6,
          },
        },
      ];
    }
    this.initData.forEach((data) => {
      data['field'] = deepClone([...field]);
      if (data.id == 'guestPrice') {
        data['field'].push({
          key: 'SIGN',
          type: 'conditionInput',
          templateOptions: {
            label: '洗车产值台数标记',
            config: {
              operators: ['EQ'],
              type: 'boolean',
              value: false,
            },
            divCol: 6,
            lblCol: 9,
            inputCol: 15,
          },
        });
      }
    });
    // this.cd.markForCheck();
  }

  getDate(type, date?) {
    let dateItem;
    switch (type) {
      case 'default' :
        dateItem = this.bi.conversionMonths(date);
        break;
      case 'year':
        dateItem = this.bi.getThisYearItem();
        break;
      case 'halfYear' :
        dateItem = this.bi.getThisHalfYearItem();
        break;
      case 'quarter':
        dateItem = this.bi.getThisQuarterItem();
        break;
      case 'lastMonth':
        dateItem = this.bi.getLastMonthItem();
        break;
      case 'thisMonth':
        dateItem = this.bi.getThisMonthItem();
        break;
      case 'lastWeek':
        dateItem = this.bi.getLastWeekItem();
        break;
      case 'nearlyDay':
        dateItem = this.bi.getNearly7DaysItem();
        break;
      case 'nowDay':
        dateItem = this.bi.getNowDayItem();
        break;
      default:
        dateItem = this.bi.conversionMonths(date);
    }
    // console.log(dateItem);
    return dateItem;
  }

  checkDateType(type) {
    let dateType;
    switch (type) {
      case 'default' :
        dateType = 'MONTH';
        break;
      case 'year':
        dateType = 'MONTH';
        break;
      case 'halfYear' :
        dateType = 'MONTH';
        break;
      case 'quarter':
        dateType = 'MONTH';
        break;
      case 'lastMonth':
        dateType = 'DAY';
        break;
      case 'thisMonth':
        dateType = 'DAY';
        break;
      case 'lastWeek':
        dateType = 'DAY';
        break;
      case 'nearlyDay':
        dateType = 'DAY';
        break;
      case 'nowDay':
        dateType = 'DAY';
        break;
      default:
        dateType = 'MONTH';
    }
    return dateType;
  }

  checkSendData(param) {
    let check = false;
    if (param.model.hasOwnProperty('DEPT_ID') && param.model['DEPT_ID'] != null) {
      check = true;
    } else {
      this.msg.error('请选择所属门店！');
    }
    return check;
  }

  refreshChartsData(param, type) {
    if (this.platform != 'zt' && !this.checkSendData(param)) {
      return;
    }
    let dateType = this.checkDateType(type);
    let dateItem = this.getDate(type, param.model['DATE']);
    const resData = {
      DATE_START: dateItem[0],
      DATE_END: dateItem[1],
      TYPE: dateType,// DAY MONTH
      ...param.model,
    };
    if (resData.hasOwnProperty('SIGN') && resData.SIGN == null) {
      resData.SIGN = false;
    }
    if (!resData.hasOwnProperty('DEPT_ID')) {
      resData['DEPT_ID'] = [];
    }

    let api = param.api;

    param.loading = true;
    this.apiService.post(api, { 'body': JSON.stringify(resData) }).subscribe((body) => {
      // console.log(param.name, body);
      let source = [param.chartsField];
      if (body && body.length != 0) {
        body.forEach((res) => {
          let data = [];
          param.chartsField.forEach((field) => {
            data.push(res[field]);
          });
          source.push([
            ...data,
          ]);
        });
        this.refreshTableData(param, body);
      }
      param['data'] = {
        dataset: {
          source: source,
        },
      };
      param.loading = false;
    });
  }

  refreshTableData(param, dataItem) {
    param.colField = [];
    param.rowData = [];
    let tRowField = param.chartsField;
    let tColField = param.tableField;
    let rowData = [];
    let colData = [];
    dataItem.forEach((data) => {
      colData.push(data[tRowField[0]]);
    });

    for (let i = 0; tColField.length > i; i++) {
      if (i > 0) {
        let field = tColField[i];
        let colField = tRowField[0];
        let key = tRowField[i];
        let data = {};
        let average = 0;
        colData.forEach((col) => {
          dataItem.forEach((item) => {
            if (item[colField] == col) {
              data[col] = item[key];
              average += item[key];
            }
          });
        });
        average = toNumber(((average / dataItem.length).toFixed(2)));
        rowData.push({ [tColField[0]]: field, ...data, '平均数': average });
      }
    }
    param.colField = [tColField[0], ...colData, '平均数'];
    param.rowData = [...rowData];
  }

  exportExcel() {
    // console.log('导出', this.initData);
    let sheets = [];

    this.initData.forEach((init) => {
      let data = [];
      let col = deepClone(init.colField);

      data = [col.map(i => i)];
      init.rowData.forEach((r) => {
        data.push(
          col.map(c => {
            let value = deepClone(r[c as string]);
            return value;
          }),
        );
      });

      sheets.push({
        data: [...data],
        name: init.name,
      });
    });

    // console.log('表格数据', sheets);
    this.xlsx.export({
      sheets: sheets,
      filename: '趋势分析报表.xlsx',
    });

  }

}

